/**
 *  列表页
 *
 * 作者 admin
 * 日期 2024-08-07 16:43:01
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-accidentReportRectify'),
        $query = $view.find('#query'),
        $accidentType = $view.find('#accidentType'),
        $accidentLevel = $view.find('#accidentLevel'),
        $searchForm = $view.find('#accidentReportRectify-table-form'),
        tableIns;

    form.verify(validate);
    form.render();
    initDictItemSelect_reportRectify();
    initTable();
    initDate();

    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#laydate-range',
            type: 'datetime',
            range: ['#start-date', '#end-date'],
        })
    }

    function initDictItemSelect_reportRectify(){
        //事故类型
        febs.initDictItemSelect($accidentType,'SAFETY_ACCIDENT_TYPE','',null);
        //事故等级
        febs.initDictItemSelect($accidentLevel,'SAFETY_ACCIDENT_LEVEL','',null);
    }
    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'accidentReportRectifyTable',
            skin: '',
            height: getTableHeight(),
            cols: [[
                {title: '序号', type: 'numbers',width: 60},
                {field: 'tenantName', title: '公司名称', minWidth: 260,hide:!hasHeadCompanyRole},
                {field: 'accidentNo',align:'center', title: '事故编号',event: 'detail', width: 200,templet:function (d) {
                        return '<p style="color:#01aaed;cursor:pointer">'+d.accidentNo+'</p>'
                    }
                },
                {field: 'accidentTitle',align:'left', title: '事故名称', minWidth: 380},
                {field: 'accidentDate',align:'center', title: '发生时间', width: 180},
                {field: 'accidentPlace',align:'left', title: '发生地点', minWidth: 280},
                {field: 'accidentType',align:'center', title: '事故类型', width: 120,templet:function (d){
                        return febs.getDictLabel(accidentTypeList,d.accidentType);
                    }
                },
                {field: 'accidentLevel',align:'center', title: '事故等级', width: 220,templet:function (d){
                        return febs.getDictLabel(accidentLevelList,d.accidentLevel);
                    }
                },
                // {field: 'reasonType',align:'center', title: '事故原因', width: 180,templet:function (d){
                //         return febs.getDictLabel(reasonTypeList,d.reasonType);
                //     }
                // },
                // {field: 'directReason', align:'center', title: '直接原因', width: 180},
                // {field: 'indirectionReason',align:'center',  title: '间接原因', width: 220},
                // {field: 'reasonContent', title: '原因概述', minWidth: 220},
                {field: 'surveyDate',align:'center', title: '调查时间', minWidth: 180},
                {field: 'obligationRealName',align:'center', title: '整改人', width: 200},
                {field: 'obligationDeptName',align:'center', title: '整改人部门', width: 200},
                {field: 'rectificationOpinion',align:'center', title: '整改措施', width: 200},
                {field: 'rectificationStatus',align:'center', title: '整改状态', width: 140, templet: function (d) {
                        var flg = '';
                        switch (d.rectificationStatus) {
                            case "2": {
                                flg = '<span class="layui-badge febs-bg-cyan">待整改</span>'
                                break;
                            }
                            case "3": {
                                flg = '<span class="layui-badge febs-bg-red">审核退回</span>'
                                break;
                            }
                            case "4": {
                                flg = '<span class="layui-badge febs-bg-gold">待审核</span>'
                                break;
                            }
                            case "5": {
                                flg = '<span class="layui-badge febs-bg-green">完成</span>'
                                break;
                            }
                        }
                        return flg;
                    }
                },
                {field: 'rectificationDeadline',align:'center', title: '整改截止时间', width: 180},
                {field: 'reportId', title: '事故id', hide:true},
                {field: 'reportId', title: '事故id', hide:true},
                {title: '操作',align:'center', fixed:'right', toolbar: '#accidentReport-option', minWidth: 120}
            ]],
            done: function (res, curr, count) {
                mergeColumn(res);
            },
        });
        tableIns.reload({url: ctx + 'accidentReport/rectifyList', where: getQueryParams(), page: {curr: 1}});
    }

    function mergeColumn(res) {
        //按字段 合并表格
        var data = res.data;
        if(commonJS.isEmpty(data)){
            return;
        }
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['tenantName','accidentNo','accidentTitle','accidentDate','accidentAreaName','accidentType','accidentLevel'];//需要合并的列名称
        var columsIndex = [1,2,3,4,5,6,7];//需要合并的列索引值
        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列

            var trArr = $view.find('.layui-table-body').find("tr");//所有行 最大问题出现在此处，获取不到表数据
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var reportId_before = data[i].reportId;
                var reportId_after = data[i-1].reportId;
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                if ((reportId_before+data[i][columsName[k]]) === (reportId_after+data[i - 1][columsName[k]]))  { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function (index,item) {//相同列的第一列增加rowspan属性
                        if(index == 0){
                            $(this).attr("rowspan", mark);
                        }

                    });
                    tdCurArr.each(function (index,item) {//当前行隐藏
                        if(index == 0){
                            $(this).css("display", "none");
                        }
                    });
                } else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;

        }
    }

    //操作列点击事件
    table.on('tool(accidentReportRectifyTable)', function(obj){
        var data = obj.data; // 获取当前行数据
        var reportId = data.reportId;
        var reportRectificationId = data.reportRectificationId;
        if(obj.event === 'detail'){
            febs.modal.open('事故上报详情', 'accidentReport/detail/'+reportId, {
                btn: ['关闭'],
                area: $(window).width() <= 750 ? ['85%', '80%']: ['95%', '95%'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
            });
        }else if (obj.event === 'rectify-record') {
            febs.modal.open('整改录入', 'accidentReport/rectifyRecord/'+reportId+'/'+reportRectificationId, {
                btn: ['保存','提交', '取消'],
                area: $(window).width() <= 750 ?  ['85%', '80%']: ['96%', '95%'],
                yes: function (index, layero) {
                    $('#reportRectifyRecord-edit').find('#save').trigger('click');
                },
                btn2: function (index, layero) {
                    $('#reportRectifyRecord-edit').find('#submit').trigger('click');
                    return false;
                },
                btn3: function () {
                    layer.closeAll();
                },
                data: {
                    tenantId: data.tenantId,
                    reportId:  data.reportId,
                    reportRectificationId:  data.reportRectificationId,
                }

            });
        }
    });

    table.on('sort(accidentReportRectifyTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    // form.on('select(rectificationDeptSelect)', function(obj){
    //     // 获取选中项 value
    //     var data={
    //         deptId : obj.value
    //     }
    //     $("#rectificationUserSelect").empty();
    //     febs.getSync(ctx + 'user/deptUserList', data, function (r) {
    //         var userList = r.data;
    //         var optionDefault = '<option value=""></option>';
    //         var options = '';
    //         $.each(userList,function (index,item) {
    //             var option =  '<option value="'+item.userId+'">'+item.uname+'</option>';
    //             options += option;
    //         })
    //         $("#rectificationUserSelect").append(optionDefault+options);
    //     });
    //     form.render();
    // });
    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    function getQueryParams() {
        return {
            businessType:'rectifyRecord',
            accidentNo: $searchForm.find('input[name="accidentNo"]').val()?.trim(),
            accidentTitle: $searchForm.find('input[name="accidentTitle"]').val()?.trim(),
            startDate: $searchForm.find('input[name="startDate"]').val(),
            endDate: $searchForm.find('input[name="endDate"]').val(),
            tenantId: $searchForm.find("select[name='tenantSelect']").find("option:selected").val(),
            rectificationUsers: $searchForm.find("input[name='rectificationUsers']").val(),
            rectificationStatus: $searchForm.find("select[name='rectificationStatus']").find("option:selected").val(),
            accidentType: $searchForm.find("select[name='accidentType']").find("option:selected").val(),
            accidentLevel: $searchForm.find("select[name='accidentLevel']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };
    }
    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});